package best.driver.android.Utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import best.driver.android.BestApp;

import java.util.UUID;

public class PhoneFunc {

    private static TelephonyManager sTelManager;

    private static WifiManager sWifiManager;


    public static void init(Context context) {
        sTelManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        sWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
    }

    /**
     * 取得sim卡的序列号
     *
     * @return sim卡序列号
     */
    public static String getSimSerialNumber() {
        String sSimSerialNumber = sTelManager.getSimSerialNumber();
        return TextUtils.isEmpty(sSimSerialNumber) ? "" : sSimSerialNumber;
    }

    /**
     * 获取imei号
     */
    public static String getImei() {
        String sImei = ((TelephonyManager) BestApp.getInstance().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE))
                .getDeviceId();
        return TextUtils.isEmpty(sImei) ? "" : sImei;
    }

    /**
     * 获取手机号
     */
    public static String getPhoneNumber() {
        return sTelManager != null ? sTelManager.getLine1Number() : null;
    }

    /**
     * 获取类型
     */
    public static int getPhoneType() {
        int type = sTelManager.getNetworkType();
        if (type == TelephonyManager.NETWORK_TYPE_GPRS // GSM网
                || type == TelephonyManager.NETWORK_TYPE_EDGE
                || type == TelephonyManager.NETWORK_TYPE_HSDPA) {
            return TelephonyManager.PHONE_TYPE_GSM;
        } else if (type == TelephonyManager.NETWORK_TYPE_CDMA // 电信cdma网
                || type == TelephonyManager.NETWORK_TYPE_1xRTT
                || type == TelephonyManager.NETWORK_TYPE_EVDO_0
                || type == TelephonyManager.NETWORK_TYPE_EVDO_A) {
            return TelephonyManager.PHONE_TYPE_CDMA;
        } else {
            return TelephonyManager.PHONE_TYPE_NONE;
        }
    }

    public static String getIMEI(String imei, String macAddr) {
        if (imei == null || imei.length() != 15) {
            imei = createFakeIMEIFromWlanMac(macAddr);
            if (imei == null) {
                imei = "101010101010103";
            }
        }
        return imei;
    }

    /**
     * 检查imei合法性
     *
     * @param imei
     */
    public static String checkIMEI(String imei) {
        if (TextUtils.isEmpty(imei)) {
            return null;
        }
        if (imei.length() == 14) {
            return imei + getIMEICheckDigit(imei);
        }
        return imei;
    }

    private static int getIMEICheckDigit(String imei)
            throws IllegalArgumentException {
        int sum = 0;
        if (imei.length() != 14) {
            throw new IllegalArgumentException(
                    "IMEI Calculate Check digit, wrong length of imei");
        }
        for (int i = 0; i < imei.length(); i++) {
            int digit = Character.digit(imei.charAt(i), 10);
            if (i % 2 != 0) {
                digit *= 2;
            }
            sum += digit / 10 + digit % 10;
        }
        sum %= 10;

        return sum == 0 ? 0 : 10 - sum;
    }

    /**
     * 根据mac地址生成imei
     *
     * @param macAddr
     * @return
     */
    private static String createFakeIMEIFromWlanMac(String macAddr) {
        if (TextUtils.isEmpty(macAddr)) {
            return null;
        }

        String imei = "";
        try {
            String[] macArray = macAddr.split(":");

            if (macArray.length == 6) {
                long mac = Long.parseLong(macArray[5]) << 0
                        | Long.parseLong(macArray[4]) << 8
                        | Long.parseLong(macArray[3]) << 16
                        | Long.parseLong(macArray[2]) << 24
                        | Long.parseLong(macArray[1]) << 32;
                imei = String.format("%014d", mac);
                imei += String.format("%d", getIMEICheckDigit(imei));
            } else {
                imei = "";
            }

        } catch (NumberFormatException e) {
            imei = "";
        } catch (Exception e) {
            imei = "";
        }
        return (imei != null && imei.length() == 0) ? null : imei;
    }

    /**
     * 呼叫电话
     *
     * @param context
     * @param phoneNumber
     * @throws Exception
     */
    public static void callPhone(Context context, String phoneNumber)
            throws Exception {
        if (context == null || TextUtils.isEmpty(phoneNumber)) {
            Toast.makeText(context, "暂时无法获取呼叫号码", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                + phoneNumber));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 发送邮件
     *
     * @param context
     * @param email_to
     * @param subject
     * @param email_body
     */
    public static void sendEmail(Context context, String email_to,
                                 String subject, String email_body) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (email_to != null) {
            intent.putExtra(Intent.EXTRA_EMAIL, new String[]{email_to});
        }
        // 设置邮件默认标题
        if (subject != null) {
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }
        // 设置要默认发送的内容
        if (email_body != null) {
            intent.putExtra(Intent.EXTRA_TEXT, email_body);
        }
        intent.setType("text/html");
        context.startActivity(Intent.createChooser(intent, ""));
    }

    /**
     * 获取mac地址
     *
     * @return
     */
    public static String getMacAddress() {
        if (sWifiManager == null) {
            return "12:34:56:78:9A:BC";
        }
        final WifiInfo info = sWifiManager.getConnectionInfo();
        String macAddress = null;
        if (info != null) {
            macAddress = info.getMacAddress();
        }
        return TextUtils.isEmpty(macAddress) ? "12:34:56:78:9A:BC" : macAddress;
    }


    /**
     * 是否开启wifi
     *
     * @param context
     * @return
     */
    public static boolean isWiFiOpen(Context context) {
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }

    public static String getUdid() {
        final String imei, tmSerial, androidId;
        imei = "" + sTelManager.getDeviceId();
        tmSerial = "" + sTelManager.getSimSerialNumber();
        androidId = "" + android.provider.Settings.Secure.getString(BestApp.getInstance().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) imei.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();
        return uniqueId;
    }

}
